﻿using System;
using System.Configuration;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace HsServerHa.Common.TCP
{
    public static class TCPClientHelper
    {
        public static CancellationToken token;
        public static Socket socket;
        public static Thread CLientThreadReceive;
        public static IPAddress ip;
        public static bool SockerClient(CancellationToken tokens, Socket socketServer)
        {
            try
            {

                token = tokens;
                if (socketServer == null||!socketServer.Connected)
                {
                    if (App.XtIP == null)
                    {
                        return false;
                    }

                    socketServer = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                    App.socketServer = socketServer;
                    App.proxSocket = socketServer;

                    socketServer.Connect(IPAddress.Parse(App.XtIP), Convert.ToInt32(ConfigurationManager.AppSettings["HeartPort"]?.ToString() ?? "6600"));
                    App.socketServer = socketServer;
                    App.proxSocket = socketServer;
                    // 定时发送心跳包
                    //Timer timer = new Timer((state) =>
                    //{
                    //    string message = "1";
                    //    byte[] data = Encoding.ASCII.GetBytes(message);
                    //    socketServer.Send(App.sendData);
                    //}, null, 0, 1000); // 每隔1秒发送一次心跳包

                    // 接收服务器的回复
                    //byte[] buffer = new byte[1024];
                    int bytesRead;
                    Task.Run(() => {
                        while ((bytesRead = socketServer.Receive(App.acceptData)) != 0)
                        {
                            string message = Encoding.ASCII.GetString(App.acceptData, 0, bytesRead);
                            //Console.WriteLine("Received: " + message);
                        }
                    });
                  


                    //socketServer = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                    //ip = IPAddress.Parse(App.XtIP);
                    //socketServer.SendTimeout = 2 * 1000;
                    //socketServer.ConnectAsync(ip, Convert.ToInt32(ConfigurationManager.AppSettings["HeartPort"]?.ToString() ?? "6600")).Wait(2 * 1000);
                    //if (socketServer.Connected)
                    //{
                    //    App.proxSocket = socketServer;
                    //    socket = socketServer;
                    //    // 开启循环接收服务器消息的线程
                    //    CLientThreadReceive = new Thread(new ThreadStart(Receive));
                    //    CLientThreadReceive.IsBackground = true;
                    //    CLientThreadReceive.Start();
                    //}
                    //else
                    //{
                    //    App.proxSocket = null;
                    //    App.socketServer = null;
                    //    return false;
                    //}


                    return true;
                }
                else
                {
                    return false;
                }
            }
            catch (Exception ex)
            {
                App.socketServer = null;
                App.proxSocket = null;
                LoggerHelper.Error(ex.Message);
                return false;
            }


        }
         
        private static void Receive()
        {
            try
            {
                while (!token.IsCancellationRequested)
                {
                    if (socket != null)
                    {
                        //实际接收到的字节数
                        int r = socket.Receive(App.acceptData);
                        if (r == 0)
                        {
                            break;
                        }
                        else
                        {
                            //判断发送的数据的类型
                            if (App.acceptData[0] == 0)  //表示发送的是文字消息
                            {
                                string str = Encoding.Default.GetString(App.acceptData, 1, r - 1);
                            }
                            //表示发送的是文件
                            if (App.acceptData[0] == 1)         // 这里后期改进为WPF中专用的
                            {

                            }
                            string str1 = Encoding.ASCII.GetString(App.acceptData);
                        }
                    }

                }

            }
            catch (Exception ex)
            {
                App.acceptData = null;
                App.acceptData=new  byte[1 * 1024];
            }
        }
    }
}
